<?php

namespace RTSCraft\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use RTSCraft\MainBundle\Controller\Util\AuthUtil;
use RTSCraft\MainBundle\Entity\Article;
use RTSCraft\MainBundle\Entity\Version;

class ArticleController extends Controller
{

      /**
     * @Route("/article/{name}", name="article")
     * @Template()
     */
  public function indexAction($name, $version = 'last')
    {
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Article');
      if ($version == 'last')
	{
	  $article = $rep->getLastVersion($name);

	  if ($article != NULL)
	    {
	      $is_auth = (AuthUtil::is_auth($this) > 0 ? false : true);

	      return $this->render('RTSCraftMainBundle:Default:article.html.twig', array('article' => $article, 'is_auth' => $is_auth));
	    }
	  else
	    {
	      $error = 'Article non trouvé';
	      return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error, 'code' => 110));
	    }
	}
      else
	{
	  $articles = $rep->getArticleAt($name, $version);
	  $article = reset($articles);
	  $isLastVersion = $rep->isLastVersion($article);

	  if ($article != NULL)
	    {
	      $is_auth = (AuthUtil::is_auth($this) > 0 ? false : true);

	      return $this->render('RTSCraftMainBundle:Default:article.html.twig', array('article' => $article, 'is_auth' => $is_auth, 'is_last' => $isLastVersion));
	    }
	  else
	    {
	      $error = 'Article non trouvé';
	      return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error, 'code' => 110));
	    }

	}
    }

    public function restoreAction($name, $version)
    {
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Article');
      $articles = $rep->getArticleAt($name, $version);
      $article = reset($articles);

      $last_version = $rep->getLastVersion($name);
      $lastnum = floatval($last_version->getNumVersion());
      $nextver = strval($lastnum + 0.1);

      // create the new version
      $new_version = new Version();
      $new_version->setText($article->getText());
      $new_version->setNumVersion($nextver);
      $new_version->setDate(new \DateTime('now'));
      $new_version->setAuthor($article->getAuthor());
      $new_version->setIp($_SERVER['REMOTE_ADDR']);
      $new_version->setArticleId($article->getArticleId());

      // push in the database
      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($new_version);
      $em->flush();

      echo '<script type="text/javascript">submitForm("article/' . $name . '")</script>';
      return new Response('ok');
    }
}
